package recommend;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlRow;

import play.libs.Json;
import views.html.*;

public class RecommendationCalculator {
	public static Date previousReqDate;
	public static boolean isReady = true;
	public static ClusterInfo clusterInfo;
	
	public synchronized static void calculate(){
		if(previousReqDate == null ||(isReady && new Date().getTime() - previousReqDate.getTime() > 24*60*60*100)){
			triggerRecommendationCalculations();
		}
	}
	
	public static void triggerRecommendationCalculations(){
		isReady = false;
		previousReqDate = new Date();
		LectureAdvisor advisor = new LectureAdvisor(getData());
		clusterInfo = advisor.extractLectureClusters();
		isReady = true;
	}
	
	
	
	public static double[][] getData(){
		
		String docCountQuery = "select count(c.course_id) docCount from edu_courses c "+ 
								"order by c.course_id;";
		int docCount = Ebean.createSqlQuery(docCountQuery).findUnique().getInteger("docCount");
		
		String s="SELECT cs.user_id,cs.course_id "+
				"FROM alekhin_edunera.edu_coursesstudents cs "+
				"where cs.user_id IN (98,99,100) "+
				"ORDER BY cs.user_id;";
		
		List<SqlRow> userCourseRows = Ebean.createSqlQuery(s).findList();
		HashMap<Integer,HashMap<Integer,Boolean>> userCourses = new HashMap<Integer,HashMap<Integer,Boolean>>();
		for (SqlRow row : userCourseRows) {
			int userId = row.getInteger("user_id");
			int courseId = row.getInteger("course_id");
			if(!userCourses.containsKey(userId)){
				userCourses.put(userId, new HashMap<Integer,Boolean>());
			}
			userCourses.get(userId).put(courseId, true);
		}
		double[][] data = new double[userCourses.keySet().size()][docCount];
		int userCount = 0;
		for (Integer userId : userCourses.keySet()) {
			for (int i = 0; i < docCount; i++) {
				if(userCourses.get(userId).containsKey(i)){
					data[userCount][i] = 1;
				}else{
					data[userCount][i] = 0;
				}
			}
		}
		return data;
		
//		return new double[][]{ 
//				new double[]{1,	1,	1,	0,	 },
//				new double[]{1,	1,	0,	1,	},
//				new double[]{0,	1,	0,	0,	}
//				};
	}

}
